<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 产品分享接口
 */
class ProductShare extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function addProductShareById($productId = NULL)
    {
        if (!$productId) {
            $this->error(__('Parameter %s can not be empty', 'productId'));
        }
        $product = model('\app\admin\model\jy\Product')->where('id', $productId)->find();
        if (!$product) {
            $this->error(__('No Results were found'));
        }
        $userId = $this->auth->id;
        $today = date("Y-m-d", time());
        $row = model('\app\admin\model\jy\ProductShare')->where(['product_id' => $productId, 'user_id' => $userId, 'create_time' => ['>=', $today]])->find();
        if ($row) {
            $row['update_time'] = date("Y-m-d H:i:s", time());
            $row->isUpdate(true)->save();
            $this->success('', $row);
        }
        Db::startTrans();
        try {
            $id = model('\app\admin\model\jy\ProductShare')->insertGetId(['product_id' => $productId, 'user_id' => $userId]);
            $product['share_count'] = $product['share_count'] + 1;
            $row = model('\app\admin\model\jy\ProductShare')->where(['product_id' => $productId, 'user_id' => $userId])->find();
            if (!$row) {
                $product['share_user_count'] = $product['share_user_count'] + 1;
            }
            $product['update_time'] = date("Y-m-d H:i:s", time());
            $product->isUpdate(true)->save();
            Db::commit();
            $this->success('', $id);
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    public function addProductShareCountByShareId($shareId = NULL)
    {
        if (!$shareId) {
            $this->error(__('Parameter %s can not be empty', 'shareId'));
        }
        $share = model('\app\admin\model\jy\ProductShare')->where('id', $shareId)->find();
        if (!$share) {
            $this->error(__('No Results were found'));
        }
        $share['click_count'] = $share['click_count'] + 1;
        $share['update_time'] = date("Y-m-d H:i:s", time());
        $share->isUpdate(true)->save();
        $this->success();
    }
}